package servlet;



import dao.UserDao;
import dao.UserDaoImpl;
import org.json.JSONObject;
import redis.RedisDao;
import redis.RedisDaoImpl;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static util.JwtUtil.validateJWT;

/**
 * @author moyv
 * @描述 修改信息页面
 */
public class ChangeServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("有个傻逼想改信息");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        先获取app过来的数据
//        System.out.println("看看是个什么玩意"+req.getParameter("psw"));
//        实践告诉我要postman模拟post请求参数不要写到body里，直接写到params里
        //        验证机制
        req.setCharacterEncoding("UTF-8");
        String token=req.getParameter("token");
        int result=0;
        if(validateJWT(token)){
            JSONObject obj=new JSONObject(req.getParameter("request"));
            String params=obj.getString("params");
            String value=obj.getString("value");
            int account=obj.getInt("account");
            UserDao dao=new UserDaoImpl();
            RedisDao dao1=new RedisDaoImpl();
            int index=0;
            switch (params){
                case "introduction":
                    index=2;
                    break;
                case "name":
                    index=0;
                    break;
                default:
            }
            if(dao.updateParams(params,value,account)&&dao1.updateUserInfo(index,account,value)){
                result=1;
            }else{
                result=2;
            }
        }else{
            System.out.println(getClass().getName()+": 非法token信息");
        }
        JSONObject obj=new JSONObject();
        obj.put("result",result);

        // 设置响应内容类型
        resp.setContentType("text/json; charset=utf-8");
//        输出数据
        PrintWriter out = resp.getWriter();
        out.print(obj);
    }
}
